/**
    @project {
        "templateId": "org.helgoboss.custom",
        "version": "0.1-SNAPSHOT",
        "dependencies": [
            "org.scala-lang:scala-library:2.9.0-1",
            "org.helgoboss:launchlet-api:0.1-SNAPSHOT",
            "org.helgoboss:scala-additions:0.1-SNAPSHOT",
            "org.helgoboss:osgi-additions:0.1-SNAPSHOT",
            "org.helgoboss:text-editor-api:0.1-SNAPSHOT"
        ]
    }
*/

package org.helgoboss.one_filer_sandbox_launchlet

import org.helgoboss.launchlet.{Launchlet, LaunchletExecutionContext}
import org.helgoboss.osgi_additions._
import org.helgoboss.osgi_additions.metatype._
import org.helgoboss.scala_additions.RichFile
import org.helgoboss.text_editor.TextEditor
import java.io.File
import java.util.Date


class Activator extends OsgiProvider with OsgiServiceWatcher with OsgiLogging {
    whenBundleActive {
        whenServicePresent[TextEditor] { 
            new CreateSandboxOneFilerLaunchlet(_).providesService[Launchlet]
        }
    }
}


class CreateSandboxOneFilerLaunchlet(textEditor: TextEditor) extends Launchlet {
    import org.helgoboss.scala_additions.Implicits._
    
    val name = "Create sandbox one-filer"
    
    def execute(executionContext: LaunchletExecutionContext) = {
        import org.helgoboss.scala_additions.Implicits._
        val oneFilerPackageName = "org.helgoboss.sandbox_" + df.format(new Date)
        val oneFilerFile = baseDir / (oneFilerPackageName + ".scala")
        baseDir.mkdirs
        val oneFilerFileContent = """/**
    @project {
        "templateId": "org.helgoboss.custom",
        "version": "0.1-SNAPSHOT",
        "dependencies": [
            "org.scala-lang:scala-library:2.9.0-1",
            "org.helgoboss:launchlet-api:0.1-SNAPSHOT",
            "org.helgoboss:scala-additions:0.1-SNAPSHOT",
            "org.helgoboss:osgi-additions:0.1-SNAPSHOT",
            "org.helgoboss:commandlet-api:0.1-SNAPSHOT",
            "org.helgoboss:commandlet-convenience:0.1-SNAPSHOT"
        ],
        "commandletId": """" + oneFilerPackageName + """"
    }
*/

package """ + oneFilerPackageName + """

import org.helgoboss.launchlet._
import org.helgoboss.commandlet._
import org.helgoboss.osgi_additions._
import org.helgoboss.scala_additions.Implicits._
import org.helgoboss.commandlet_convenience.Implicits._

class Activator extends OsgiProvider {
    whenBundleActive {
        new Commandlet {
            val id = """" + oneFilerPackageName + """"
            def execute(context: ExecutionContext) = {
                val out = context.writer
                out.println("Hello world!")
                0
            }
        }.providesService[Commandlet]
    }
}
"""
        oneFilerFile.content = oneFilerFileContent
        textEditor.open(List(oneFilerFile))
    }
    private val df = new java.text.SimpleDateFormat("yyyyMMdd_HHmmss")
    private val baseDir = RichFile.tempDir / "sandbox-one-filers"
}